package com.ming.service.impl;

import com.ming.pojo.vo.FileUploadVO;
import com.ming.service.FileService;
import com.ming.service.strategy.FileUploadStrategy;
import com.ming.service.strategy.FileUploadStrategyFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

/**
 * 文件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    // 允许上传的文件类型
    private static final String[] ALLOWED_FILE_TYPES = {
            "image/jpeg", "image/png", "image/gif", "image/webp",
            "application/pdf", "text/plain",
            "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    };

    // 最大文件大小：10MB
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    private final FileUploadStrategyFactory strategyFactory;

    @Override
    public FileUploadVO uploadFile(MultipartFile file) throws IOException {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 2. 检查文件类型
        String contentType = file.getContentType();
        if (!isAllowedFileType(contentType)) {
            throw new IllegalArgumentException("不支持的文件类型: " + contentType);
        }

        // 3. 检查文件大小
        long fileSize = file.getSize();
        if (!isAllowedFileSize(fileSize)) {
            throw new IllegalArgumentException("文件大小超过限制，最大允许10MB");
        }

        // 4. 获取文件上传策略并执行上传
        FileUploadStrategy strategy = strategyFactory.getStrategy();
        String originalFilename = file.getOriginalFilename();

        return strategy.uploadFile(file, originalFilename, contentType, fileSize);
    }

    @Override
    public void deleteFile(String filename) throws IOException {
        // 获取文件上传策略并执行删除
        FileUploadStrategy strategy = strategyFactory.getStrategy();
        strategy.deleteFile(filename);
    }

    @Override
    public boolean isAllowedFileType(String contentType) {
        return Arrays.asList(ALLOWED_FILE_TYPES).contains(contentType);
    }

    @Override
    public boolean isAllowedFileSize(long fileSize) {
        return fileSize <= MAX_FILE_SIZE;
    }

    @Override
    public String getCurrentStorageType() {
        return strategyFactory.getStrategy().getStorageType();
    }
}